<template>
  <el-dialog
    :close-on-click-modal="false"
    title="设备报废计划"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="报废单号" prop="number">
            <el-input v-model="form.number" readonly :disabled="disableForm" placeholder="自动生成" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="申请单位" prop="unit">
            <el-input v-model="form.unit" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请日期" prop="applyTime">
            <el-date-picker v-model="form.applyTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="showTargetSetListModal = true">引入设备</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:payTime="{row:{payTime}}">
          {{ dateFormat(payTime) }}
        </template>
        <template v-slot:useYears="{row}">
          <el-input v-model="row.useYears" />
        </template>
        <template v-slot:oldYears="{row}">
          <el-input v-model="row.oldYears" />
        </template>
        <template v-slot:reason="{row}">
          <el-input v-model="row.reason" />
        </template>
        <template v-slot:options="{row}">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRow(row)">删除</el-button>
        </template>

      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <!-- <deviceList title="易耗品台账列表" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{api:getConsumableLedgerList}" @getSelectedRows="getSelectedRows" /> -->
    <tree-modal title="机械设备选择(多选)" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{tree:getMachineDirectoryTree,list:getMachineDeviceDetailList}" @getSelectedRows="getSelectedRows" />

  </el-dialog>
</template>

<script>
import { addDeviceScrapPlanInfo, updateDeviceScrapPlanInfo, getDeviceScrapPlanInfoDetail } from '@/api/consumableManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
// import deviceList from './deviceList'
import treeModal from './machineSelect.vue'

import { getConsumableLedgerList } from '@/api/consumableManage'
import { getMachineDirectoryTree, getMachineDeviceDetailList } from '@/api/basicCode'

import moment from 'moment'
import { turnMap, deviceScrapPlan } from './config.js'
export default {
  name: 'AddDeviceScrapPlanInfo',
  components: {
    fileUploader,
    // deviceList,
    treeModal
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getConsumableLedgerList,
      getMachineDirectoryTree,
      getMachineDeviceDetailList,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        number: '',
        unit: '机械处',
        applyTime: ''
      },
      columns: [
        {
          label: '设备编号',
          prop: 'name'
        },
        {
          label: '设备名称',
          prop: 'number',
          width: '180'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '厂家',
          prop: 'factory'
        },
        {
          label: '购置时间',
          prop: 'payTime',
          slot: 'payTime',
          width: '90'
        },
        {
          label: '使用年限',
          prop: 'useYears',
          slot: 'useYears'
        },
        {
          label: '规定折旧年限',
          slot: 'oldYears',
          width: '100'
        },
        {
          label: '购置原值',
          prop: 'payValue'
        },
        {
          label: '报废原因',
          prop: 'reason',
          slot: 'reason',
          width: '150'
        },
        {
          label: '所在地',
          prop: 'address',
          width: '150'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '120',
          prop: 'options',
          slot: 'options'
        }
        // {
        //   fixed: 'right',
        //   prop: 'options',
        //   slot: 'options'
        // }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        name: [
          { required: true, message: '单位名称', trigger: 'change' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val) {
        if (this.optType !== 'add') {
          this.getDocDetail(this.data.id)
          this.$nextTick(() => {
            Object.keys(this.form).forEach(key => {
              const source = this.data[key]
              if (typeof source === 'boolean') {
                this.form[key] = source ? 1 : 0
              } else {
                this.form[key] = source
              }
            })
          })
        }
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    delRow(data) {
      this.$confirm('确定要删除该数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.targetList.indexOf(data)
        if (index > -1) {
          this.targetList.splice(index, 1)
        }
      }).catch(() => {
      })
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRows(data) {
      // this.targetList = this.targetList.concat(data.map(item => {
      //   return {
      //     ...item
      //   }
      // }))
      this.targetList = this.targetList.concat(data.map(item => {
        const {
          // deviceDirectoryCode: devDirCode,
          // deviceDirectoryName: devDirName,
          payAmount: payValue,
          devNumber: number,
          devName: name,
          specification,
          factoryName: factory,
          payTime,
          address
        } = item
        return {
          name, number, specification, payValue, factory,
          payTime, address,
          oldYears: '',
          useYears: '', reason: ''
        }
      }))
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getDeviceScrapPlanInfoDetail({ deviceScrapPlanInfoId: id }).then(res => {
        const { lstAttachment, lstDeviceScrapPlanDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstDeviceScrapPlanDetail && lstDeviceScrapPlanDetail.length > 0) {
          this.targetList = lstDeviceScrapPlanDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    // 数据处理
    dealData(obj) {
      const tmpObj = {}
      for (const key in deviceScrapPlan) {
        const val = turnMap[key]
        tmpObj[key] = obj[key] ? obj[key] : obj[val]
      }
      return tmpObj
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const tmpArr = []
          this.targetList.map(item => {
            const tmpObj = this.dealData(item)
            tmpArr.push(tmpObj)
          })
          const params = {
            deviceScrapPlanInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstDeviceScrapPlanDetail: tmpArr
          }
          const fn = this.optType === 'add' ? addDeviceScrapPlanInfo : updateDeviceScrapPlanInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
